<template>
  <div class="checkout-container">
    <div class="checkout-header animate__animated animate__fadeInDown">
      <h2><i class="el-icon-shopping-bag-1"></i> 订单结算</h2>
      <el-button type="primary" icon="el-icon-arrow-left" @click="goBack">返回购物车</el-button>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <el-card v-else class="checkout-content animate__animated animate__fadeIn">
      <!-- 收货地址 -->
      <div class="section-title">
        <i class="el-icon-location"></i> 收货地址
      </div>
      <div class="address-section">
        <div v-if="selectedAddress" class="selected-address">
          <div class="address-info">
            <div class="address-contact">
              <span class="name">{{ selectedAddress.name }}</span>
              <span class="phone">{{ selectedAddress.phone }}</span>
              <el-tag size="small" type="success" v-if="selectedAddress.isDefault">默认</el-tag>
            </div>
            <div class="address-detail">{{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detailAddress }}</div>
          </div>
          <div class="address-actions">
            <el-button type="text" @click="showAddressDrawer">更换地址</el-button>
          </div>
        </div>
        <div v-else class="no-address">
          <el-button type="primary" @click="showAddressForm">+ 添加收货地址</el-button>
        </div>
      </div>

      <!-- 商品清单 -->
      <div class="section-title">
        <i class="el-icon-shopping-cart-2"></i> 商品清单
      </div>
      <div class="products-section">
        <el-table :data="selectedItems" border>
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column label="商品信息" min-width="300">
            <template slot-scope="scope">
              <div class="product-info">
                <div class="product-image">
                  <img src="https://via.placeholder.com/60" alt="商品图片" />
                </div>
                <div class="product-name">{{ scope.row.productName }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
          <el-table-column label="小计" width="120">
            <template slot-scope="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 配送方式 -->
      <div class="section-title">
        <i class="el-icon-truck"></i> 配送方式
      </div>
      <div class="delivery-section">
        <el-radio-group v-model="deliveryMethod">
          <el-radio :label="1">普通配送</el-radio>
          <el-radio :label="2">快速配送 (额外费用: ¥10)</el-radio>
        </el-radio-group>
      </div>

      <!-- 支付方式 -->
      <div class="section-title">
        <i class="el-icon-money"></i> 支付方式
      </div>
      <div class="payment-section">
        <el-radio-group v-model="paymentMethod">
          <el-radio :label="1">在线支付</el-radio>
          <el-radio :label="2">货到付款</el-radio>
        </el-radio-group>
      </div>

      <!-- 订单备注 -->
      <div class="section-title">
        <i class="el-icon-document"></i> 订单备注
      </div>
      <div class="remark-section">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入订单备注信息"
          v-model="orderRemark">
        </el-input>
      </div>

      <!-- 订单金额 -->
      <div class="order-summary">
        <div class="summary-item">
          <span>商品总额：</span>
          <span>¥{{ totalAmount.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span>配送费用：</span>
          <span>¥{{ deliveryFee.toFixed(2) }}</span>
        </div>
        <div class="summary-total">
          <span>应付金额：</span>
          <span class="total-price">¥{{ (totalAmount + deliveryFee).toFixed(2) }}</span>
        </div>
      </div>

      <!-- 提交订单 -->
      <div class="order-submit">
        <div class="submit-summary">
          <div class="submit-count">
            共 <strong>{{ totalItems }}</strong> 件商品，
            总计：<span class="total-price">¥{{ (totalAmount + deliveryFee).toFixed(2) }}</span>
          </div>
        </div>
        <el-button type="primary" size="large" @click="submitOrder" :loading="submitting" :disabled="!canSubmit">
          提交订单
        </el-button>
      </div>
    </el-card>

    <!-- 地址选择抽屉 -->
    <el-drawer
      title="选择收货地址"
      :visible.sync="addressDrawerVisible"
      direction="rtl"
      size="50%">
      <div class="address-list">
        <el-radio-group v-model="selectedAddressId">
          <div v-for="address in addressList" :key="address.id" class="address-item">
            <el-radio :label="address.id">
              <div class="address-radio-content">
                <div class="address-info">
                  <div class="address-contact">
                    <span class="name">{{ address.name }}</span>
                    <span class="phone">{{ address.phone }}</span>
                    <el-tag size="small" type="success" v-if="address.isDefault">默认</el-tag>
                  </div>
                  <div class="address-detail">{{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailAddress }}</div>
                </div>
              </div>
            </el-radio>
          </div>
        </el-radio-group>
        
        <div class="address-actions-drawer">
          <el-button type="primary" @click="selectAddress">确认选择</el-button>
          <el-button @click="showAddressForm">添加新地址</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 添加地址表单对话框 -->
    <el-dialog title="添加收货地址" :visible.sync="addressFormVisible" width="50%">
      <el-form :model="addressForm" :rules="addressRules" ref="addressForm" label-width="100px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" required>
          <el-cascader
            v-model="addressRegion"
            :options="regionOptions"
            @change="handleRegionChange"
            placeholder="请选择所在地区">
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="addressForm.detailAddress" type="textarea" :rows="2" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认收货地址</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addressFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAddress" :loading="savingAddress">保存</el-button>
      </div>
    </el-dialog>

    <!-- 订单提交成功对话框 -->
    <el-dialog
      title="订单提交成功"
      :visible.sync="orderSuccessVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false">
      <div class="order-success">
        <i class="el-icon-success success-icon"></i>
        <h3>订单提交成功</h3>
        <p>订单号: {{ createdOrderId }}</p>
        <div class="order-success-actions">
          <el-button @click="goToOrders">查看订单</el-button>
          <el-button type="primary" @click="goToHome">继续购物</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'animate.css/animate.min.css';

export default {
  name: 'Checkout',
  data() {
    return {
      loading: true,
      submitting: false,
      savingAddress: false,
      selectedItems: [],
      addressList: [],
      selectedAddress: null,
      selectedAddressId: null,
      addressDrawerVisible: false,
      addressFormVisible: false,
      orderSuccessVisible: false,
      createdOrderId: '',
      currentUser: null,
      deliveryMethod: 1,
      paymentMethod: 1,
      orderRemark: '',
      addressForm: {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
      },
      addressRegion: [],
      regionOptions: [
        // 简化版中国省市区数据
        {
          value: '河南省',
          label: '河南省',
          children: [
            {
              value: '郑州市',
              label: '郑州市',
              children: [
                { value: '中原区', label: '中原区' },
                { value: '二七区', label: '二七区' },
                { value: '金水区', label: '金水区' }
              ]
            },
            {
              value: '洛阳市',
              label: '洛阳市',
              children: [
                { value: '西工区', label: '西工区' },
                { value: '老城区', label: '老城区' },
                { value: '涧西区', label: '涧西区' }
              ]
            }
          ]
        },
        {
          value: '山东省',
          label: '山东省',
          children: [
            {
              value: '济南市',
              label: '济南市',
              children: [
                { value: '历下区', label: '历下区' },
                { value: '市中区', label: '市中区' },
                { value: '槐荫区', label: '槐荫区' }
              ]
            }
          ]
        }
      ],
      addressRules: {
        name: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    // 计算商品总金额
    totalAmount() {
      return this.selectedItems.reduce((total, item) => {
        return total + (item.price * item.quantity);
      }, 0);
    },
    // 计算商品总数量
    totalItems() {
      return this.selectedItems.reduce((total, item) => {
        return total + item.quantity;
      }, 0);
    },
    // 计算配送费用
    deliveryFee() {
      return this.deliveryMethod === 1 ? 0 : 10;
    },
    // 是否可以提交订单
    canSubmit() {
      return this.selectedItems.length > 0 && this.selectedAddress !== null;
    }
  },
  created() {
    this.getCurrentUser();
    this.loadCartItems();
    this.loadAddresses();
  },
  methods: {
    // 获取当前登录用户
    getCurrentUser() {
      try {
        const userStr = localStorage.getItem('user');
        if (userStr) {
          this.currentUser = JSON.parse(userStr);
        }
        
        if (!this.currentUser || !this.currentUser.id) {
          this.$message.warning('您尚未登录，请先登录系统');
          this.$router.push('/login');
        }
      } catch (error) {
        console.error('获取用户信息失败', error);
        this.$message.error('获取用户信息失败');
      }
    },
    
    // 加载购物车中选中的商品
    loadCartItems() {
      if (!this.currentUser || !this.currentUser.id) {
        this.loading = false;
        return;
      }
      
      this.loading = true;
      this.request.get(`/cart/findByUserId/${this.currentUser.id}`).then(res => {
        this.loading = false;
        if (res.code === '200') {
          // 只选择已勾选的购物车项
          if (res.data && Array.isArray(res.data)) {
            this.selectedItems = res.data.filter(item => item.selected === true || item.selected === 1);
          } else {
            this.selectedItems = [];
          }
          
          // 如果没有选中商品，提示用户并返回购物车
          if (this.selectedItems.length === 0) {
            this.$message.warning('请先选择要结算的商品');
            this.$router.push('/cart');
          }
        } else {
          this.$message.error('获取购物车失败: ' + (res.msg || '未知错误'));
        }
      }).catch(err => {
        this.loading = false;
        console.error('加载购物车失败:', err);
        this.$message.error('网络错误，无法加载购物车');
      });
    },
    
    // 加载用户收货地址
    loadAddresses() {
      if (!this.currentUser || !this.currentUser.id) {
        return;
      }
      
      // 模拟从后端加载地址
      // 实际项目中应该从后端API获取
      setTimeout(() => {
        this.addressList = [
          {
            id: 1,
            name: '张三',
            phone: '13800138000',
            province: '河南省',
            city: '郑州市',
            district: '金水区',
            detailAddress: '文化路77号',
            isDefault: true
          },
          {
            id: 2,
            name: '李四',
            phone: '13900139000',
            province: '山东省',
            city: '济南市',
            district: '历下区',
            detailAddress: '解放路88号',
            isDefault: false
          }
        ];
        
        // 设置默认地址
        const defaultAddress = this.addressList.find(addr => addr.isDefault);
        if (defaultAddress) {
          this.selectedAddress = defaultAddress;
          this.selectedAddressId = defaultAddress.id;
        } else if (this.addressList.length > 0) {
          this.selectedAddress = this.addressList[0];
          this.selectedAddressId = this.addressList[0].id;
        }
      }, 500);
    },
    
    // 显示地址选择抽屉
    showAddressDrawer() {
      this.addressDrawerVisible = true;
    },
    
    // 显示添加地址表单
    showAddressForm() {
      this.addressFormVisible = true;
      this.addressRegion = [];
      this.addressForm = {
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
      };
    },
    
    // 确认选择地址
    selectAddress() {
      const address = this.addressList.find(addr => addr.id === this.selectedAddressId);
      if (address) {
        this.selectedAddress = address;
        this.addressDrawerVisible = false;
      } else {
        this.$message.warning('请选择一个收货地址');
      }
    },
    
    // 地区选择变更
    handleRegionChange(value) {
      if (value && value.length === 3) {
        this.addressForm.province = value[0];
        this.addressForm.city = value[1];
        this.addressForm.district = value[2];
      }
    },
    
    // 保存收货地址
    saveAddress() {
      this.$refs.addressForm.validate((valid) => {
        if (valid) {
          if (!this.addressForm.province || !this.addressForm.city || !this.addressForm.district) {
            this.$message.warning('请选择所在地区');
            return;
          }
          
          this.savingAddress = true;
          
          // 模拟保存地址
          // 实际项目中应该调用后端API保存
          setTimeout(() => {
            this.savingAddress = false;
            const newAddress = {
              id: this.addressList.length + 1,
              ...this.addressForm
            };
            
            // 如果设为默认地址，将其他地址设为非默认
            if (newAddress.isDefault) {
              this.addressList.forEach(addr => {
                addr.isDefault = false;
              });
            }
            
            this.addressList.push(newAddress);
            this.selectedAddress = newAddress;
            this.selectedAddressId = newAddress.id;
            this.addressFormVisible = false;
            
            this.$message.success('收货地址添加成功');
          }, 500);
        }
      });
    },
    
    // 提交订单
    submitOrder() {
      if (!this.canSubmit) {
        if (!this.selectedAddress) {
          this.$message.warning('请选择收货地址');
        } else if (this.selectedItems.length === 0) {
          this.$message.warning('没有选中的商品');
        }
        return;
      }
      
      this.submitting = true;
      
      // 由于后端只支持单个商品的订单，我们需要为每个选中商品创建一个订单
      const createOrderPromises = this.selectedItems.map(item => {
        // 构建订单数据
        const orderData = {
          userId: this.currentUser.id,
          productId: item.productId,
          quantity: item.quantity,
          deliveryAddress: this.formatAddress(this.selectedAddress)
        };
        
        console.log('创建订单数据:', orderData);
        
        // 发送请求创建订单
        return this.request.post('/order/create', orderData);
      });
      
      // 等待所有订单创建完成
      Promise.all(createOrderPromises)
        .then(results => {
          this.submitting = false;
          
          // 检查是否所有订单都创建成功
          const successResults = results.filter(res => res.code === '200');
          if (successResults.length === createOrderPromises.length) {
            // 所有订单都创建成功
            this.createdOrderId = successResults[0].data; // 使用第一个订单ID显示
            this.orderSuccessVisible = true;
            
            // 清空购物车中已选中的商品
            this.clearSelectedItems();
          } else {
            // 部分订单创建失败
            this.$message.warning(`部分订单创建失败，成功创建 ${successResults.length}/${createOrderPromises.length} 个订单`);
          }
        })
        .catch(err => {
          this.submitting = false;
          console.error('创建订单失败:', err);
          this.$message.error('网络错误，无法创建订单');
        });
    },
    
    // 格式化地址为字符串
    formatAddress(address) {
      if (!address) return '';
      return `${address.name} ${address.phone} ${address.province}${address.city}${address.district}${address.detailAddress}`;
    },
    
    // 清空已选中的购物车商品
    clearSelectedItems() {
      if (!this.currentUser || !this.currentUser.id) {
        return;
      }
      
      // 获取已选中商品的ID列表
      const cartIds = this.selectedItems.map(item => item.cartId);
      
      // 逐个删除购物车商品
      const deletePromises = cartIds.map(cartId => {
        return this.request.delete(`/cart/deleteById/${cartId}`);
      });
      
      Promise.all(deletePromises).catch(err => {
        console.error('清空购物车失败:', err);
      });
    },
    
    // 跳转到订单列表
    goToOrders() {
      this.orderSuccessVisible = false;
      this.$router.push('/order');
    },
    
    // 跳转到首页继续购物
    goToHome() {
      this.orderSuccessVisible = false;
      this.$router.push('/shop');
    },
    
    // 返回购物车
    goBack() {
      this.$router.push('/cart');
    }
  }
}
</script>

<style scoped>
.checkout-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.checkout-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.checkout-header h2 {
  margin: 0;
  color: #303133;
}

.loading-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin-top: 20px;
}

.checkout-content {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  padding: 10px 0;
  margin-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.section-title i {
  margin-right: 5px;
  color: #409EFF;
}

.address-section {
  margin-bottom: 20px;
}

.selected-address {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: a4px;
}

.address-contact {
  margin-bottom: 5px;
}

.address-contact .name {
  font-weight: bold;
  margin-right: 10px;
}

.address-contact .phone {
  color: #606266;
}

.address-detail {
  color: #606266;
}

.no-address {
  text-align: center;
  padding: 30px 0;
}

.products-section {
  margin-bottom: 20px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 60px;
  height: 60px;
  margin-right: 10px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-name {
  font-size: 14px;
  color: #303133;
}

.delivery-section, .payment-section, .remark-section {
  margin-bottom: 20px;
}

.order-summary {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #606266;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  color: #303133;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #dcdfe6;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
}

.order-submit {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.submit-summary {
  margin-right: 20px;
}

.address-list {
  padding: 20px;
}

.address-item {
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.address-radio-content {
  padding-left: 10px;
}

.address-actions-drawer {
  margin-top: 20px;
  text-align: center;
}

.order-success {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 60px;
  color: #67c23a;
  margin-bottom: 15px;
}

.order-success h3 {
  margin-bottom: 10px;
  color: #303133;
}

.order-success p {
  margin-bottom: 20px;
  color: #606266;
}

.order-success-actions {
  margin-top: 20px;
}
</style> 